package com.kt.emall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.kt.common.to.es.SkuEsModel;
import com.kt.emall.search.config.EmallElasticSearchConfig;
import com.kt.emall.search.constant.EsConstant;
import com.kt.emall.search.service.MallSearchService;
import com.kt.emall.search.vo.SearchParam;
import com.kt.emall.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Description:
 * Created with IntelliJ IDEA.
 *
 * @author: KamTeng
 * Date: 2021/8/18
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {

    /**
     * split.length == 2 or 1
     */
    private static final Integer SPLIT_LENGTH_2 = 2;
    private static final Integer SPLIT_LENGTH_1 = 1;

    /**
     * 作为split分割使用
     */
    private static final String SPLIT_SYMBOL = "_";




    @Autowired
    private RestHighLevelClient client;

    @Override
    public SearchResult search(SearchParam param) {
        // 动态构建出查询需要的DSL语句
        SearchResult result = null;
        // 1、准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);
        try {
            // 2、执行检索请求
            SearchResponse response = client.search(searchRequest, EmallElasticSearchConfig.COMMON_OPTIONS);
            // 3、分析响应数据，封装成我们需要的格式
            result = buildSearchResult(response, param);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 准备检索请求
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        // 构建DSL语句的
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        /*查询：模糊匹配、过滤(按照属性、分类、品牌、加个区间、库存)*/
        // 1、构建bool - query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 1.1、must - 模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        // 1.2、bool - filter - 按照三级分类id查询
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        // 1.3、bool - filter - 按照品牌id查询
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        // 1.2、bool - filter - 按照所有的属性进行查询
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            // 由于是String[]格式的attrs，所以可以通过便利获取每个attr字符串
            for (String attr : param.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] split = attr.split("_");
                // 检索的属性ID
                String attrId = split[0];
                // 检索的属性值
                String[] attrValues = split[1].split("_");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                // 每一个都必须生成一个nested查询，所以Builder须放在for循环内
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        // 1.2、bool - filter - 按照是否有库存进行查询
        if (param.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }
        // 1.2、bool - filter - 按照加个区间查询
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            /*
              "range": {
                  "skuPrice": {
                      "gte": 0,
                      "lte":500
                  }
              }
             */
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] split = param.getSkuPrice().split(SPLIT_SYMBOL);
            // 价格是一个区间
            if (split.length == SPLIT_LENGTH_2) {
                rangeQuery.gte(split[0]).lte(split[1]);
            } else if (split.length == SPLIT_LENGTH_1) {
                if (param.getSkuPrice().startsWith(SPLIT_SYMBOL)) {
                    rangeQuery.lte(split[0]);
                }
                if (param.getSkuPrice().endsWith(SPLIT_SYMBOL)) {
                    rangeQuery.gte(split[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
        // 把上面所有的查询条件都组合作为query的参数 ↓
        searchSourceBuilder.query(boolQuery);

        /*排序、分页、高亮*/
        // 2.1、排序
        if (!StringUtils.isEmpty(param.getSort())) {
            // sort=hotScore_asc/desc
            String paramSort = param.getSort();
            String[] typeName = paramSort.split("_");
            SortOrder sortOrder = "asc".equalsIgnoreCase(typeName[1]) ? SortOrder.ASC : SortOrder.DESC;
            searchSourceBuilder.sort(typeName[0], sortOrder);
        }
        // 2.2、分页  pageSize:5
        // pageNum:1    from:0  size:5  [0,1,2,3,4]
        // pageNUm:2    from:5  size:5
        // from = (pageNum - 1) * size
        searchSourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        // 2.3、高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            // 需要高亮的内容
            highlightBuilder.field("skuTitle");
            // 前置标签
            highlightBuilder.preTags("<b style='color:red'>");
            // 后置标签
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }

        // 查看DSL语句
        System.out.println("DSL====>" + searchSourceBuilder);


        /*聚合分析*/
        // 1、品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg");
        brandAgg.field("brandId").size(50);
        // 1.1、品牌聚合的子聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        // TODO 1、聚合brand
        // 品牌聚合完成
        searchSourceBuilder.aggregation(brandAgg);
        // 2、分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        // TODO 2、聚合catalog
        searchSourceBuilder.aggregation(catalogAgg);

        // 3、属性聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        // 聚合出当前所有的attrId
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        // 聚合分析出当前attr_id对应的名字
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        // 聚合分析出当前attr_id对应的所有可能的属性值attrValue
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attrAgg.subAggregation(attrIdAgg);
        // TODO 3、聚合attr
        searchSourceBuilder.aggregation(attrAgg);
        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
    }


    /**
     * 构建结果数据
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        SearchResult searchResult = new SearchResult();
        // 1、返回所有查询到的所有商品
        SearchHits hits = response.getHits();
        List<SkuEsModel> esModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            // 便利所有击中记录
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String highLightString = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(highLightString);
                }
                esModels.add(skuEsModel);
            }
        }
        searchResult.setProducts(esModels);
        // 2、当前所有商品涉及到的所有属性信息
        List<SearchResult.AttrVO> attrVos = new ArrayList<>();
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg =  attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVO attrVO = new SearchResult.AttrVO();
            // 1、得到属性ID
            long attrId = bucket.getKeyAsNumber().longValue();
            // 2、得到属性名字
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            // 3、得到属性所有值
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg"))
                                    .getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString)
                                    .collect(Collectors.toList());
            attrVO.setAttrId(attrId);
            attrVO.setAttrName(attrName);
            attrVO.setAttrValue(attrValues);

            attrVos.add(attrVO);
        }
        searchResult.setAttrs(attrVos);
        // 3、当前所有商品涉及到的所有品牌信息
        List<SearchResult.BrandVO> brandVoS = new ArrayList<>();
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandVO brandVO = new SearchResult.BrandVO();
            // 1、得到品牌的ID
            long brandId = bucket.getKeyAsNumber().longValue();
            // 2、得到品牌的名字
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            // 3、得到品牌的图片
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVO.setBrandId(brandId);
            brandVO.setBrandName(brandName);
            brandVO.setBrandImg(brandImg);
            brandVoS.add(brandVO);
        }
        searchResult.setBrands(brandVoS);
        // 4、当前所有商品涉及到的所有分类信息
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVO> catalogVoS = new ArrayList<>();
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            SearchResult.CatalogVO catalogVO = new SearchResult.CatalogVO();
            String keyAsString = bucket.getKeyAsString();
            // 得到分类ID
            catalogVO.setCatalogId(Long.parseLong(keyAsString));
            // 通过子聚合得到分类名
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVO.setCatalogName(catalogName);
            catalogVoS.add(catalogVO);
        }
        searchResult.setCatalogs(catalogVoS);
        // ======以上是从聚合信息获取======

        // 5、分页信息 - 页码
        searchResult.setPageNum(param.getPageNum());
        // 6、分页信息 - 总记录数
        long total = hits.getTotalHits().value;
        searchResult.setTotal(total);
        // 7、分页信息 - 总页码 - 计算  11/2 = 5 ... 1
        int pageSize = EsConstant.PRODUCT_PAGESIZE;
        int totalPages = (int)total % pageSize == 0 ? pageSize : ((int)total / pageSize + 1);
        searchResult.setTotalPages(totalPages);
        return searchResult;
    }
}